﻿using BuyThePeople.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;

namespace BuyThePeople.Controllers
{
    public class GoodsController : Controller
    {
        //
        // GET: /Goods/

        public ActionResult Index()
        {
            return Redirect("~/Goods/List");
        }

        public ActionResult List(string id, string sort)
        {
            GoodsList gList = new GoodsList();

            sort = string.IsNullOrEmpty(sort) ? "new" : sort;
            gList.page = string.IsNullOrEmpty(id) ? 1 : int.Parse(id);

            DataModelsDataContext dmdc = new DataModelsDataContext();

            if (sort.Equals("close"))
            {
                // 마감임박
                gList.goods = dmdc.T_GOODS.OrderByDescending(x => x.BidDateEnd - new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day)).ToList();
            }
            else if (sort.Equals("order"))
            {
                // 주문자 많은 순
                gList.goods = dmdc.T_GOODS.OrderByDescending(x => dmdc.T_JOINTPURCHASE.Count(item => item.GoodsSeq == x.GoodsSeq)).ToList();
            }
            else
            {
                // 최근순
                gList.goods = dmdc.T_GOODS.OrderByDescending(x => x.RegDate).ToList();
            }

            if (gList.goods == null)
            {
                return Redirect(ConstFactory.UrlError);
            }

            gList.CalcPage();
            ViewBag.sort = sort;

            return View(gList);
        }

        public ActionResult Detail(string id)
        {
            ViewBag.Id = id;

            int goodsId;
            //Request.Headers;
            if (string.IsNullOrEmpty(id) || !int.TryParse(id, out goodsId))
            {
                return Redirect(ConstFactory.UrlError);
            }
            else
            {
                ViewBag.url = ConstFactory.UrlGoodsDetail+id;

                DataModelsDataContext dmdc = new DataModelsDataContext();
                Goods goods = new Goods();

                goods.goods = dmdc.T_GOODS.FirstOrDefault(x => x.GoodsSeq.Equals(id));

                if (goods.goods == null) return Redirect(ConstFactory.UrlError);

                goods.commentList = dmdc.T_COMMENT.Where(x => x.GoodsSeq.Equals(id)).Select(x => x).ToList();
                goods.goods.Detail = string.IsNullOrEmpty(goods.goods.Detail) ? "" : goods.goods.Detail.Replace("&lt", "<").Replace("&gt", ">");

                return View(goods);
            }
        }

        public ActionResult Make()
        {
            if (Session[ConstFactory.SessionUser] is UserLoginData)
            {
                return View();
            }
            else
            {
                return Redirect(string.Format("{0}?url={1}", ConstFactory.UrlLogin, ConstFactory.UrlGoodsMake));
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Make(T_GOODS g)
        {
            g.RegDate = DateTime.Now;
            g.Detail = g.Detail.Replace("<", "&lt").Replace(">", "&gt");

            DataModelsDataContext dmdc = new DataModelsDataContext();
            dmdc.T_GOODS.InsertOnSubmit(g);
            dmdc.SubmitChanges();

            return Redirect("~/Goods/Detail/" + dmdc.T_GOODS.Max(x => x.GoodsSeq));
        }

        public ActionResult APISearch(string searchText)
        {
            return View();
        }

        public ActionResult Join(string id)
        {
            int goodsSeq;
            if (string.IsNullOrEmpty(id) || !int.TryParse(id, out goodsSeq))
            {
                return new EmptyResult();
            }

            int count = -1;
            string msg = "이미 참여하셨습니다.";

            if (Session[ConstFactory.SessionUser] is UserLoginData)
            {
                var user = Session[BuyThePeople.ConstFactory.SessionUser] as BuyThePeople.Models.UserLoginData;
                int user_seq = user.UserSeq;

                DataModelsDataContext dmdc = new DataModelsDataContext();
                int cnt = dmdc.T_JOINTPURCHASE.Count(item => item.GoodsSeq == goodsSeq && item.UserSeq == user_seq);

                if (cnt <= 0)
                {
                    T_JOINTPURCHASE j = new T_JOINTPURCHASE();
                    j.GoodsSeq = goodsSeq;
                    j.UserSeq = user_seq;
                    j.RegDate = DateTime.Now;

                    dmdc.T_JOINTPURCHASE.InsertOnSubmit(j);
                    dmdc.SubmitChanges();

                    count = dmdc.T_JOINTPURCHASE.Count(item => item.GoodsSeq == goodsSeq);
                    msg = "정상적으로 참여되었습니다.";
                }
            }
            else
            {
                count = -2;
                msg = "로그인이 필요한 서비스입니다.";
            }

            return Json("{count: '" + count + "', msg: '" + msg + "'}", JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Comment(string id, string commentText)
        {
            int goodsSeq;
            if (string.IsNullOrEmpty(id) || !int.TryParse(id, out goodsSeq))
            {
                return new EmptyResult();
            }

            int result = -1;
            string data = "";
            if (Session[ConstFactory.SessionUser] is UserLoginData)
            {
                var user = Session[BuyThePeople.ConstFactory.SessionUser] as BuyThePeople.Models.UserLoginData;
                int user_seq = user.UserSeq;

                T_COMMENT t = new T_COMMENT();
                t.Comment = commentText;
                t.GoodsSeq = goodsSeq;
                t.UserSeq = user_seq;
                t.RegDate = DateTime.Now;

                DataModelsDataContext dmdc = new DataModelsDataContext();
                dmdc.T_COMMENT.InsertOnSubmit(t);
                dmdc.SubmitChanges();

                result = 1;
                data = "{comment: '" + t.Comment + "', userName: '" + user.Name + "', regDate: '" + t.RegDate.Value.ToShortDateString() + "'}";
            }
            else
            {
                data = "'로그인이 필요한 서비스입니다.'";
            }
            

            return Json("{result: '"+result+"', data: "+data+"}", JsonRequestBehavior.AllowGet);
        }

        public ActionResult Bid(string id, string price)
        {
            int goodsSeq;
            if (string.IsNullOrEmpty(id) || !int.TryParse(id, out goodsSeq))
            {
                return new EmptyResult();
            }

            int result = -1;
            string data = "";
            if (Session[ConstFactory.SessionUser] is UserLoginData)
            {
                var user = Session[BuyThePeople.ConstFactory.SessionUser] as BuyThePeople.Models.UserLoginData;
                int user_seq = user.UserSeq;

                T_BIDDING b = new T_BIDDING();
                b.GoodsSeq = goodsSeq;
                b.UserSeq = user_seq;
                b.Price = int.Parse(price);
                b.RegDate = DateTime.Now;

                DataModelsDataContext dmdc = new DataModelsDataContext();
                dmdc.T_BIDDING.InsertOnSubmit(b);
                dmdc.SubmitChanges();

                result = 1;
                data = "'정상적으로 입찰되었습니다.'";
            }
            else
            {
                data = "'로그인이 필요한 서비스입니다.'";
            }

            return Json("{result: '" + result + "', msg: " + data + "}", JsonRequestBehavior.AllowGet);
        }

        public ActionResult Search(string id, string page)
        {
            ViewBag.Search = id;
            GoodsList gList = new GoodsList();

            int p;
            gList.page = string.IsNullOrEmpty(page) || !int.TryParse(page, out p) ? 1 : p;

            DataModelsDataContext dmdc = new DataModelsDataContext();

            // 마감임박
            gList.goods = dmdc.T_GOODS.Where(x => x.Title.IndexOf(id) >= 0).ToList();

            if (gList.goods == null)
            {
                gList.goods = new List<T_GOODS>();
            }

            gList.CalcPage();

            return View(gList);
        }

        public string NaverProxy(string url)
        {
            WebClient c = new WebClient();
            string res = c.DownloadString("http://openapi.naver.com/shorturl.json?key=4bb15f73c6f2ddf274ae1e45f582acdf&url="+url);
            return res;
        }

    }
}
